package danran.dbapi.controller;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSONObject;
import danran.dbapi.domain.DataSource;
import danran.dbapi.service.DataSourceService;
import danran.dbapi.utils.DruidPoolManager;
import danran.dbapi.utils.JDBCUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @Classname TableController
 * @Description TODO
 * @Date 2022/1/17 15:59
 * @Created by RanCoder
 */
@RestController
@RequestMapping("/table")
public class TableController {

    @Autowired
    DataSourceService dataSourceService;

    @RequestMapping("/getAllTables")
    public List<JSONObject> getAllTables(String sourceId) {
        if (sourceId == null) return new ArrayList<>();
        DataSource ds = dataSourceService.getDataSourceById(sourceId);
        // 从druid中获得connection
        try {
            AtomicReference<DruidPooledConnection> connection =
                    new AtomicReference<>(DruidPoolManager.getPooledConnection(ds));

            List<String> allTables = JDBCUtil.getAllTables(connection.get(), ds.getTableSql());
            if (allTables == null) {
                return new ArrayList<>();
            }
            List<JSONObject> data = allTables.stream().map(t -> {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("label", t);
                try {
                    if (connection.get().isClosed()) {
                        connection.set(DruidPoolManager.getPooledConnection(ds));
                    }
                    jsonObject.put("columns", JDBCUtil.getRDBMSColumnProperties(connection.get(), ds.getType(), t));
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                jsonObject.put("showColumns", false);
                return jsonObject;
            }).collect(Collectors.toList());
            return data;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    @RequestMapping("/getAllColumns")
    public List<JSONObject> getAllColumns(String datasourceId, String table) throws SQLException {
        DataSource ds = dataSourceService.getDataSourceById(datasourceId);
        return JDBCUtil.getRDBMSColumnProperties(DruidPoolManager.getPooledConnection(ds), ds.getType(), table);
    }
}
